package com.iss.itemplate.service.imp;

import com.iss.itemplate.dao.HelloDao;
import com.iss.itemplate.domain.App;
import com.iss.itemplate.dto.AppDto;
import com.iss.itemplate.service.GenericService;
import com.iss.itemplate.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.iss.itemplate.util.Utils;
import com.iss.itemplate.util.ITemplateConstants;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Date;

import dxci.component.upload.FileUploader;
import dxci.component.upload.UploadRequest;
import dxci.component.upload.UploadResult;
import org.apache.commons.io.FileUtils;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;


/**
 * **********************************************************************
 * <p/>
 * iServiceSoft Inc © - 2009 All Rights Reserved
 * _____________________________________________
 * <p/>
 * NOTICE:  All information contained herein is, and remains
 * the property of iServiceSoft. Intellectual and technical concepts
 * contained herein are proprietary of iServiceSoft and may be covered
 * by U.S. and Foreign Patents, patents in process, and are protected
 * by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from iServiceSoft Incorporated.
 * <p/>
 * ***********************************************************************
 */

@Service("helloService")
public class HelloServiceImp extends GenericService implements HelloService {
   @Autowired
   @Qualifier("helloDaoJpa")
   private HelloDao helloDao;

   @Override
   public String getAppName () {
      return helloDao.getAppName();
   }

   @Override
   public AppDto getApp() {
      return mapper.map(helloDao.getApp(), AppDto.class, APP_INFO);
   }

   @Override
   @Transactional(propagation = Propagation.REQUIRED)
   public void insertApp(AppDto appDto) {
      App app = mapper.map(appDto, App.class, APP_INFO);
      helloDao.insert(app);
   }

   @Override
   @Transactional(propagation = Propagation.REQUIRED)
   public void updateApp(AppDto appDto) {
      App app = mapper.map(appDto, App.class, APP_INFO);
      helloDao.update(app);
   }

   @Override
   @Transactional(propagation = Propagation.REQUIRED)
   public void deleteApp(Long appId) {
      App app = helloDao.findById(appId);
      helloDao.delete(app);
   }

   @Override
   public void sendEclaim(String contextPath) {
      // path Eclaim file
      String eClaimText = "E:/isoftwork/ClaimStatus/iTemplate-web/target"
            + ITemplateConstants.PRE_PERSISTENT_FOLDER
            + ITemplateConstants.INSURANCE_ECLAIM_PREFIX  + "/eClaim_"
            + ITemplateConstants.NAME_ECLAIM + ".txt";
      // path Eclaim response file
      String eClaimResponse = "E:/isoftwork/ClaimStatus/iTemplate-web/target"
            + ITemplateConstants.PRE_PERSISTENT_FOLDER
            + ITemplateConstants.INSURANCE_ECLAIM_RESPONSE_PREFIX + "/eClaim_Response_"
            + ITemplateConstants.NAME_ECLAIM + ".txt";

      // send Eclaim
      String strResponse = "";
      File eClaimFile = new File(eClaimText);
      if (eClaimFile.isFile() && eClaimFile.exists()) {
         UploadRequest request = new UploadRequest();
         request.setUsername(ITemplateConstants.ECLAIM_USERNAME);
         request.setPassword(ITemplateConstants.ECLAIM_PASSWORD);
         request.setSource("EDI");
         request.setFile(eClaimFile);
         URL url;
         UploadResult response;
         String status = "";
         String timeResponse = "";
         String authenticationId = "";
         String errorMessage = "";
         String errorDetails = "";
         try {
            url = new URL(ITemplateConstants.ECLAIM_URL);
            request.setUrl(url);
            response = FileUploader.authenticateAndUpload(request);
            strResponse = response.toString();
            int intStatus = response.getStatus();
            if (intStatus == 0) {
               status = "Success";
               timeResponse = response.getTimestamp().toString();
            } else {
               status = "Failure";
               Calendar cal = Calendar.getInstance();
               Date date = cal.getTime();
               timeResponse = date.toString();
            }
            authenticationId = response.getAuthenticationId();
            errorMessage = response.getErrorMessage();
         } catch (Exception e) {
            StringBuffer sb = new StringBuffer();
            sb.append("Status").append("=").append("Failure").append("\r\n");
            status = "Failure";
            sb.append("ErrorMessage").append("=").append(e.getMessage()).append("\r\n");
            errorMessage = e.getMessage();
            StringWriter s = new StringWriter();
            PrintWriter pw = new PrintWriter(s);
            e.printStackTrace(pw);
            sb.append("ErrorDetails").append("=").append(s.toString()).append("\r\n");
            errorDetails = s.toString();
            strResponse = sb.toString();
            Calendar cal = Calendar.getInstance();
            Date date = cal.getTime();
            timeResponse = date.toString();
         }
      }

      // writte info response
      File eClaimResponseFile = new File(eClaimResponse);
      eClaimResponseFile.delete();
      if (!eClaimResponseFile.exists()) {
         try {
            FileUtils.writeStringToFile(eClaimResponseFile, strResponse, "ASCII");
         }  catch (Exception e) {

         }
      }
   }

   @Override
   public void sendEligibility() {
      // path Eclaim file
      String eligibilityText = "E:/isoftwork/ClaimStatus/iTemplate-web/target"
            + ITemplateConstants.PRE_PERSISTENT_FOLDER
            + ITemplateConstants.ELIGIBILITY_REQUEST_PREFIX
            + "/" + ITemplateConstants.NAME_ElIGIBILITY + ".xml";

      String eligibilityResponse = "E:/isoftwork/ClaimStatus/iTemplate-web/target"
            + ITemplateConstants.PRE_PERSISTENT_FOLDER
            + ITemplateConstants.ELIGIBILITY_RESPONSE_PREFIX
            + "/" + ITemplateConstants.NAME_ElIGIBILITY + ".xml";
      try {
         SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
         SOAPConnection soapConnection = soapConnectionFactory.createConnection();

         //set trust store for request
         String keystorePath = "E:/isoftwork/ClaimStatus/iTemplate-web/target"
               + ITemplateConstants.PRE_PERSISTENT_FOLDER
               + ITemplateConstants.ELIGIBILITY_REQUEST_PREFIX + "/DentalXChangeKeyStore";
         System.setProperty("javax.net.ssl.trustStore", keystorePath);
         System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

         // Send SOAP Message to SOAP Server
         byte[] encoded = Files.readAllBytes(Paths.get(eligibilityText));
         InputStream bStream = new ByteArrayInputStream(encoded);

         // request
         SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(null, bStream);

         // get response
         SOAPMessage soapResponse = soapConnection.call(soapMessage, ITemplateConstants.URL_ELIGIBILITY);
         soapConnection.close();

         // write response
         File outputXmlPathDir = new File(eligibilityResponse);
         outputXmlPathDir.delete();
         soapResponse.writeTo(new FileOutputStream(outputXmlPathDir));
      } catch (Exception ex) {
         StringWriter sw = new StringWriter();
         ex.printStackTrace(new PrintWriter(sw));
      }
   }
}
